<template>
  <view class="basic-info-form">
    <view class="content-header">
      <view class="header-left">
        <i
          class="iconfont icon-lianxiren"
          style="font-size: 24px; color: #7c3aed"
        ></i>
        <text class="section-title">基本信息</text>
      </view>
    </view>

    <!-- 使用 uni-forms 进行表单校验 -->
    <uni-forms
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      label-width="300px"
    >
      <!-- 动态渲染表单模块 -->
      <view
        v-for="module in config.modules"
        :key="module.key"
        class="info-module"
      >
        <view class="module-header">
          <view class="module-icon">
            <i
              :class="`iconfont icon-${module.icon}`"
              style="font-size: 16px; color: #ffffff"
            ></i>
          </view>
          <view class="module-title">
            <text class="title">{{ module.title }}</text>
            <text class="subtitle">{{ module.subtitle }}</text>
          </view>
        </view>

        <view class="module-content">
          <!-- 动态渲染字段行 -->
          <view v-for="row in module.rows" :key="row.key" class="form-grid">
            <!-- 动态渲染字段 -->
            <view
              v-for="field in getVisibleFields(row.fields)"
              :key="field.key"
              class="form-item"
              :class="{ 'full-width': field.fullWidth }"
            >
              <!-- 文本输入框 -->
              <uni-forms-item
                v-if="field.type === 'input'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <uni-easyinput
                  v-model="(formData as any)[field.key]"
                  :placeholder="field.placeholder"
                  :type="(field.inputType as any) || 'text'"
                  :maxlength="field.maxlength"
                  :disabled="field.disabled"
                  @blur="handleFieldChange(field.key, $event)"
                />
              </uni-forms-item>

              <!-- 文本域 -->
              <uni-forms-item
                v-else-if="field.type === 'textarea'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <uni-easyinput
                  v-model="(formData as any)[field.key]"
                  type="textarea"
                  :placeholder="field.placeholder"
                  :disabled="field.disabled"
                  @blur="handleFieldChange(field.key, $event)"
                />
              </uni-forms-item>

              <!-- 选择器 -->
              <uni-forms-item
                v-else-if="field.type === 'select'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <uni-data-select
                  v-model="(formData as any)[field.key]"
                  :localdata="getFieldOptions(field)"
                  :placeholder="field.placeholder"
                  :disabled="field.disabled"
                  @change="handleFieldChange(field.key, $event)"
                />
              </uni-forms-item>

              <!-- 日期选择器 -->
              <uni-forms-item
                v-else-if="field.type === 'date'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <!-- 身份证有效期特殊处理：如果显示状态为长期有效，显示为文本而不是日期选择器 -->
                <template
                  v-if="
                    field.key === 'IdCardExpiryDate' &&
                    idCardExpiryDisplayState === 'long-term'
                  "
                >
                  <uni-easyinput
                    :value="'长期有效'"
                    :disabled="true"
                    :placeholder="field.placeholder"
                  />
                </template>
                <!-- 正常的日期选择器 -->
                <template v-else>
                  <uni-datetime-picker
                    v-model="(formData as any)[field.key]"
                    type="date"
                    :disabled="field.disabled"
                    @change="handleFieldChange(field.key, $event)"
                  />
                </template>
                <view v-if="field.tips" class="form-tips">
                  <text>{{ field.tips }}</text>
                </view>
              </uni-forms-item>

              <!-- 自定义部门选择器 -->
              <uni-forms-item
                v-else-if="field.type === 'custom-department-picker'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <XenDepartmentPicker
                  v-model="(formData as any)[field.key]"
                  :placeholder="field.placeholder"
                  :department-data="rawDepartmentData"
                  @change="handleCustomDepartmentChange"
                />
                <view v-if="field.tips" class="form-tips">
                  <text>{{ field.tips }}</text>
                </view>
              </uni-forms-item>

              <!-- 人像照片拍摄 -->
              <uni-forms-item
                v-else-if="field.type === 'portrait-camera'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <view class="portrait-camera-container">
                  <!-- 预览和操作区域 -->
                  <view class="portrait-preview-area">
                    <!-- 已上传照片的预览 -->
                    <view
                      v-if="(formData as any)[field.key]"
                      class="portrait-preview"
                    >
                      <image
                        :src="getImageUrl((formData as any)[field.key])"
                        class="portrait-image"
                        mode="aspectFit"
                        @tap="handlePortraitPreview(field)"
                      />
                      <!-- 右上角删除按钮 -->
                      <button
                        class="delete-icon-button"
                        @click="deletePortraitPhoto(field)"
                      >
                        <uni-icons
                          type="clear"
                          size="32"
                          color="#727476"
                        ></uni-icons>
                      </button>
                    </view>

                    <!-- 未上传时的拍摄按钮 -->
                    <view v-else class="portrait-capture">
                      <button
                        class="capture-trigger"
                        @click="handlePortraitCapture(field)"
                      >
                        <uni-icons
                          type="camera"
                          size="40"
                          color="#7881de"
                        ></uni-icons>
                        <text class="capture-text">{{
                          field.placeholder
                        }}</text>
                      </button>
                    </view>
                  </view>

                  <!-- 提示信息 -->
                  <view v-if="field.tips" class="upload-tips">
                    <text>{{ field.tips }}</text>
                  </view>
                </view>
              </uni-forms-item>

              <!-- 文件上传 -->
              <uni-forms-item
                v-else-if="field.type === 'file'"
                :name="field.key"
                :label="field.label"
                :required="field.required"
              >
                <view class="file-upload-container">
                  <!-- 特殊处理身份证照片上传 -->
                  <template v-if="field.isIdCard">
                    <uni-file-picker
                      v-model="fileValues[field.key]"
                      :fileMediatype="
                        (field.fileConfig?.mediatype as any) || 'image'
                      "
                      :mode="(field.fileConfig?.mode as any) || 'grid'"
                      :limit="field.fileConfig?.limit || 1"
                      :title="field.fileConfig?.title || field.placeholder"
                      :imageStyles="field.fileConfig?.imageStyles"
                      :delIcon="true"
                      @select="(e) => selectIdCardFile(field.key, e)"
                      @success="(e) => uploadIdCardSuccess(field.key, e)"
                      @fail="(e) => uploadIdCardFail(field.key, e)"
                      @delete="(e) => deleteIdCardFile(field.key, e)"
                    ></uni-file-picker>
                  </template>
                  <!-- 普通文件上传 -->
                  <template v-else>
                    <uni-file-picker
                      v-model="fileValues[field.key]"
                      :fileMediatype="
                        (field.fileConfig?.mediatype as any) || 'image'
                      "
                      :mode="(field.fileConfig?.mode as any) || 'grid'"
                      :limit="field.fileConfig?.limit || 1"
                      :title="field.fileConfig?.title || field.placeholder"
                      :imageStyles="field.fileConfig?.imageStyles"
                      :delIcon="true"
                      @select="(e) => selectFile(field.key, e)"
                      @success="(e) => uploadFileSuccess(field.key, e)"
                      @fail="(e) => uploadFileFail(field.key, e)"
                      @delete="(e) => deleteFile(field.key, e)"
                    ></uni-file-picker>
                  </template>

                  <!-- 提示信息 -->
                  <view v-if="field.tips" class="upload-tips">
                    <text>{{ field.tips }}</text>
                  </view>
                </view>
              </uni-forms-item>

              <!-- 岗位选择器的特殊提示 -->
              <view
                v-if="
                  field.key === 'JobPositionId' &&
                  formData.GroupId &&
                  getFieldOptions(field).length === 0
                "
                class="form-tips"
              >
                <text style="color: #999; font-size: 12px">
                  该部门暂无可选岗位，请联系管理员配置岗位信息
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-forms>

    <!-- 保存按钮 -->
    <view class="section-actions">
      <button
        class="custom-button primary-button"
        @click="handleSave"
        :disabled="isSaving"
      >
        <i
          class="iconfont icon-gouxuan"
          style="font-size: 16px; color: #ffffff; margin-right: 4px"
        ></i>
        {{ isSaving ? "保存中..." : "保存基本信息" }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  defineProps,
  defineEmits,
  nextTick,
  onMounted,
  onUnmounted,
  computed,
} from "vue";
import { onShow } from "@dcloudio/uni-app";
import { uploadImage } from "../../../../utils/unirequest";
import type { ISysPersonRepairBill } from "../../api/interface";
import useActivityApi from "../../api/index";
import type { IUserInfo } from "../../../../pages/login/api/interface";
import { basicInfoFormConfig, type FieldConfig } from "./basicInfoFormConfig";
import XenDepartmentPicker from "@/components/XenDepartmentPicker.vue";

// 定义props
interface Props {
  modelValue: Partial<ISysPersonRepairBill>;
  isSaving?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  isSaving: false,
});

// 定义emits
const emits = defineEmits<{
  "update:modelValue": [value: Partial<ISysPersonRepairBill>];
  save: [formData: Partial<ISysPersonRepairBill>];
}>();

// 表单配置
const config = ref(basicInfoFormConfig);

// 表单引用
const formRef = ref();

// 文件上传值存储
const fileValues = ref<Record<string, any[]>>({});

// 身份证有效期显示状态控制
const idCardExpiryDisplayState = ref<"normal" | "long-term">("normal");

// 表单校验规则
const formRules = computed(() => {
  const rules: Record<string, any> = {};

  config.value.modules.forEach((module) => {
    module.rows.forEach((row) => {
      row.fields.forEach((field) => {
        const fieldRules: any[] = [];

        // 必填验证
        if (field.required) {
          let actionText = "输入";
          if (field.type === "select" || field.type === "tree-select") {
            actionText = "选择";
          } else if (field.type === "file") {
            actionText = "上传";
          }

          fieldRules.push({
            required: true,
            errorMessage: `请${actionText}${field.label}`,
          });
        }

        // 正则验证
        if (field.pattern) {
          fieldRules.push({
            pattern: field.pattern,
            errorMessage:
              field.patternErrorMessage || `${field.label}格式不正确`,
          });
        }

        if (fieldRules.length > 0) {
          rules[field.key] = {
            rules: fieldRules,
          };
        }
      });
    });
  });

  return rules;
});

// 获取可见字段（处理条件显示）
const getVisibleFields = (fields: FieldConfig[]) => {
  return fields.filter((field) => {
    if (field.dependsOn && field.dependsOnValue !== undefined) {
      return (
        formData.value[field.dependsOn as keyof typeof formData.value] ===
        field.dependsOnValue
      );
    }
    return true;
  });
};

// 获取字段选项
const getFieldOptions = (field: FieldConfig) => {
  if (field.key === "OrgId") {
    return orgOptions.value;
  }
  if (field.key === "JobPositionId") {
    return jobPositionOptions.value;
  }
  return field.options || [];
};

// 内部表单数据
const formData = ref<Partial<ISysPersonRepairBill>>({
  ID: null,
  BillCode: null,
  BillStatus: 1,
  WorkflowStatus: 1,
  Remark: "",
  Approver: null,
  ApprovalTime: null,
  Name: "",
  StaffNo: "",
  BirthDate: null,
  Age: null,
  Gender: null, // 现在是文字：男、女、其他
  Ethnicity: null, // 现在是文字：汉族、回族、满族、蒙古族、壮族、其他
  HighestEducation: null, // 现在是文字：小学、初中、高中、中专、大专、本科、研究生、硕士、博士、博士后、博士研究生、其他
  MajorCategory: null, // 专业大类
  MajorName: null, // 专业名称
  MaritalStatus: null, // 现在是文字：未婚、已婚、离异、丧偶
  FertilityStatus: null, // 生育状况：未育、一育、二育、三育、四育、四育及以上
  PhotoId: null,
  IdCardNo: "",
  IdCardFrontPhotoId: null,
  IdCardBackPhotoId: null,
  IdCardExpiryDate: null,
  HouseholdRegistration: "",
  NativePlace: "",
  PoliticalStatus: null, // 现在是文字：群众、共青团员、中共党员、无党派人士、其他
  PartyJoinDate: null,
  PartyBranch: "",
  ArchiveLocation: "",
  ArchiveNo: "",
  ArchiveTransferOutDate: null,
  ArchiveTransferInDate: null,
  HomeAddress: "",
  Phone: "",
  Email: "",
  SalaryBank: "",
  SalaryAccount: "",
  BonusBank: "",
  BonusAccount: "",
  OrgId: null,
  GroupId: null,
  JobPositionId: null,
  HireDate: null,
  ConfirmationDate: null,
  EmploymentType: null,
  ContractType: null,
  ContractNo: null,
  ContractStartDate: null,
  ContractEndDate: null,
  BloodType: null, // 现在是文字：A、B、AB、O、其他
  Hobbies: "",
  JoinWorkDate: null, // 参加工作时间
  ArchiveAgeDate: null, // 档案年龄日期
  WorkYears: 0, // 工龄
  CompanyYears: 0, // 司龄
  IsVeteran: null, // 是否退伍军人 (字符串: "true"/"false")
  VeteranCertificateId: null, // 退伍证图片ID
  ...props.modelValue,
});

// 文件上传处理函数
const selectFile = async (fieldKey: string, e: any) => {
  const filePath = e.tempFiles[0].path || e.tempFiles[0].tempFilePath;
  if (filePath) {
    try {
      const fileId = await uploadImage(filePath);
      (formData.value as any)[fieldKey] = fileId;

      // 更新file-picker显示的数据
      fileValues.value[fieldKey] = [
        {
          name: e.tempFiles[0].name || "文件",
          url: getImageUrl(fileId),
          extname: e.tempFiles[0].extname || "pdf",
          size: e.tempFiles[0].size || 0,
          fileID: fileId,
        },
      ];

      // 触发表单验证更新
      nextTick(() => {
        if (formRef.value) {
          formRef.value.clearValidate(fieldKey);
        }
      });
    } catch (error) {
      uni.showToast({
        title: "文件上传失败，请重试",
        icon: "none",
      });
    }
  }
};

const uploadFileSuccess = (_fieldKey: string, _e: any) => {
  // 文件上传成功
};

const uploadFileFail = (_fieldKey: string, _e: any) => {
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

const deleteFile = (fieldKey: string, _e: any) => {
  (formData.value as any)[fieldKey] = null;
  fileValues.value[fieldKey] = [];

  // 触发表单验证更新
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField(fieldKey);
    }
  });
};

// 身份证文件上传处理
const selectIdCardFile = async (fieldKey: string, e: any) => {
  const filePath = e.tempFiles[0].path || e.tempFiles[0].tempFilePath;
  if (filePath) {
    try {
      const fileId = await uploadImage(filePath);
      (formData.value as any)[fieldKey] = fileId;

      // 更新file-picker显示的数据
      fileValues.value[fieldKey] = [
        {
          name: e.tempFiles[0].name || "身份证照片",
          url: getImageUrl(fileId),
          extname: e.tempFiles[0].extname || "jpg",
          size: e.tempFiles[0].size || 0,
          fileID: fileId,
        },
      ];

      // 触发表单验证更新
      nextTick(() => {
        if (formRef.value) {
          formRef.value.clearValidate(fieldKey);
        }
      });

      // 触发身份证识别
      if (fieldKey === "IdCardFrontPhotoId") {
        await recognizeIdentityCard(fileId, "front");
      } else if (fieldKey === "IdCardBackPhotoId") {
        await recognizeIdentityCard(fileId, "back");
      }
    } catch (error) {
      uni.showToast({
        title: "身份证照片上传失败，请重试",
        icon: "none",
      });
    }
  }
};

const uploadIdCardSuccess = (_fieldKey: string, _e: any) => {
  // 身份证照片上传成功
};

const uploadIdCardFail = (_fieldKey: string, _e: any) => {
  uni.showToast({
    title: "身份证照片上传失败，请重试",
    icon: "none",
  });
};

const deleteIdCardFile = (fieldKey: string, _e: any) => {
  (formData.value as any)[fieldKey] = null;
  fileValues.value[fieldKey] = [];

  // 触发表单验证更新
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField(fieldKey);
    }
  });
};

// 工作信息选项数据
const orgOptions = ref<{ value: string; text: string }[]>([]);
const groupOptions = ref<{ value: string; text: string }[]>([]);
const jobPositionOptions = ref<{ value: string; text: string }[]>([]);

// 部门树数据 - 用于级联选择器
const departmentTreeData = ref<any[]>([]);
// 原始部门数据 - 用于自定义部门选择器
const rawDepartmentData = ref<any[]>([]);

// 部门选择器的ref
const departmentPicker = ref<any>(null);

// 数据加载状态标志位，用于区分数据回显和用户操作
const isDataLoading = ref(false);
// 部门确认框状态标志位，防止重复弹框
const isConfirming = ref(false);

// 这些计算属性已经不再需要，因为现在通过配置驱动处理

// 注意：移除了复杂的GroupId watch监听器，改为在用户操作时直接处理部门选择逻辑

// 注意：移除了监听部门ID变化的watch，因为会导致输入其他字段时也触发岗位加载
// 现在岗位加载只在以下情况触发：
// 1. 数据回显时（props.modelValue watch 和 loadData 方法）
// 2. 用户主动选择部门时（selectDepartment 函数）

// API实例
const api = useActivityApi();

// 用户信息
const userInfo = ref<IUserInfo | null>(null);

// 身份证识别功能
const recognizeIdentityCard = async (
  imageId: string,
  cardType: "front" | "back",
) => {
  try {
    uni.showLoading({
      title: "正在识别身份证信息...",
      mask: true,
    });

    const response = await api.recognizeIdentityCard({
      ImageId: imageId,
      CardType: cardType,
    });

    uni.hideLoading();

    if (response.Code === 200 && response.Data) {
      const data = response.Data;

      if (cardType === "front") {
        // 验证是否确实是身份证正面（正面应该包含姓名、身份证号等基本信息）
        const hasFrontInfo =
          data.Name || data.IdNumber || data.Gender || data.BirthDate;
        const hasBackInfo = data.IssuingAuthority || data.ValidPeriod;

        if (!hasFrontInfo && hasBackInfo) {
          // 用户上传了身份证反面，但选择的是正面
          // 清理错误上传的图片数据
          formData.value.IdCardFrontPhotoId = null;
          fileValues.value["IdCardFrontPhotoId"] = [];

          // 强制刷新UI组件和触发验证更新
          nextTick(() => {
            // 已清除身份证正面错误图片，等待重新上传
            if (formRef.value) {
              formRef.value.validateField("IdCardFrontPhotoId");
            }
          });

          uni.showModal({
            title: "上传错误",
            content:
              "检测到您上传的是身份证反面，但当前需要上传身份证正面。图片已清除，请重新选择身份证正面照片上传。",
            confirmText: "重新上传",
            showCancel: false,
          });
          return;
        }

        if (!hasFrontInfo) {
          // 无法识别出正面信息
          // 清理可能有问题的图片数据
          formData.value.IdCardFrontPhotoId = null;
          fileValues.value["IdCardFrontPhotoId"] = [];

          // 强制刷新UI组件和触发验证更新
          nextTick(() => {
            // 已清除身份证正面问题图片，等待重新上传
            if (formRef.value) {
              formRef.value.validateField("IdCardFrontPhotoId");
            }
          });

          uni.showModal({
            title: "识别异常",
            content:
              "无法从图片中识别出身份证正面信息。图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证正面\n2. 照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示",
            confirmText: "我知道了",
            showCancel: false,
          });
          return;
        }

        // 身份证正面信息
        if (data.Name) {
          formData.value.Name = data.Name;
        }
        if (data.Gender) {
          // 直接使用性别文字
          formData.value.Gender = data.Gender;
        }
        if (data.Nationality) {
          // 根据民族名称设置对应的文字值
          const ethnicityMap: Record<string, string> = {
            汉: "汉族",
            汉族: "汉族",
            壮: "壮族",
            壮族: "壮族",
            满: "满族",
            满族: "满族",
            回: "回族",
            回族: "回族",
            蒙古: "蒙古族",
            蒙古族: "蒙古族",
          };
          formData.value.Ethnicity = ethnicityMap[data.Nationality] || "其他"; // 默认为其他
        }
        if (data.BirthDate) {
          // 处理各种可能的日期格式
          const birthDateStr = data.BirthDate.toString();
          let parsedDate: Date | null = null;

          try {
            // 情况1: 中文格式 (如：1990年10月1日)
            if (/^\d{4}年\d{1,2}月\d{1,2}日$/.test(birthDateStr)) {
              const match = birthDateStr.match(
                /^(\d{4})年(\d{1,2})月(\d{1,2})日$/,
              );
              if (match) {
                const year = parseInt(match[1]);
                const month = parseInt(match[2]);
                const day = parseInt(match[3]);
                parsedDate = new Date(year, month - 1, day);
              }
            }
            // 情况2: YYYYMMDD 格式 (如：20130506)
            else if (/^\d{8}$/.test(birthDateStr)) {
              const year = birthDateStr.substring(0, 4);
              const month = birthDateStr.substring(4, 6);
              const day = birthDateStr.substring(6, 8);
              parsedDate = new Date(
                parseInt(year),
                parseInt(month) - 1,
                parseInt(day),
              );
            }
            // 情况3: YYYY-MM-DD 格式
            else if (/^\d{4}-\d{2}-\d{2}$/.test(birthDateStr)) {
              parsedDate = new Date(birthDateStr + "T00:00:00");
            }
            // 情况4: YYYY.MM.DD 格式
            else if (/^\d{4}\.\d{2}\.\d{2}$/.test(birthDateStr)) {
              const normalizedDate = birthDateStr.replace(/\./g, "-");
              parsedDate = new Date(normalizedDate + "T00:00:00");
            }
            // 情况5: YYYY/MM/DD 格式
            else if (/^\d{4}\/\d{2}\/\d{2}$/.test(birthDateStr)) {
              const normalizedDate = birthDateStr.replace(/\//g, "-");
              parsedDate = new Date(normalizedDate + "T00:00:00");
            }
            // 情况6: 其他格式，尝试直接解析
            else {
              parsedDate = new Date(birthDateStr);
            }

            // 验证日期是否有效
            if (parsedDate && !isNaN(parsedDate.getTime())) {
              // uni-datetime-picker 需要 YYYY-MM-DD 格式的字符串
              const year = parsedDate.getFullYear();
              const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
              const day = String(parsedDate.getDate()).padStart(2, "0");
              const dateString = `${year}-${month}-${day}`;

              formData.value.BirthDate = parsedDate;

              // 触发字段变化事件，确保UI更新
              handleFieldChange("BirthDate", dateString);
            }
          } catch (error) {
            // 解析出生日期出错
          }
        }
        if (data.Address) {
          // 身份证地址信息填入户口所在地和籍贯
          formData.value.HouseholdRegistration = data.Address;
          formData.value.NativePlace = data.Address;
        }
        if (data.IdNumber) {
          formData.value.IdCardNo = data.IdNumber;
        }

        uni.showToast({
          title: "身份证正面信息识别成功",
          icon: "success",
        });
      } else if (cardType === "back") {
        // 验证是否确实是身份证反面（反面应该包含签发机关、有效期等信息）
        const hasBackInfo = data.IssuingAuthority || data.ValidPeriod;
        const hasFrontInfo =
          data.Name || data.IdNumber || data.Gender || data.BirthDate;

        if (!hasBackInfo && hasFrontInfo) {
          // 用户上传了身份证正面，但选择的是反面
          // 清理错误上传的图片数据
          formData.value.IdCardBackPhotoId = null;
          fileValues.value["IdCardBackPhotoId"] = [];

          // 强制刷新UI组件和触发验证更新
          nextTick(() => {
            // 已清除身份证反面错误图片，等待重新上传
            if (formRef.value) {
              formRef.value.validateField("IdCardBackPhotoId");
            }
          });

          uni.showModal({
            title: "上传错误",
            content:
              "检测到您上传的是身份证正面，但当前需要上传身份证反面。图片已清除，请重新选择身份证反面照片上传。",
            confirmText: "重新上传",
            showCancel: false,
          });
          return;
        }

        if (!hasBackInfo) {
          // 无法识别出反面信息
          // 清理可能有问题的图片数据
          formData.value.IdCardBackPhotoId = null;
          fileValues.value["IdCardBackPhotoId"] = [];

          // 强制刷新UI组件和触发验证更新
          nextTick(() => {
            // 已清除身份证反面问题图片，等待重新上传
            if (formRef.value) {
              formRef.value.validateField("IdCardBackPhotoId");
            }
          });

          uni.showModal({
            title: "识别异常",
            content:
              "无法从图片中识别出身份证反面信息。图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证反面\n2. 照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示",
            confirmText: "我知道了",
            showCancel: false,
          });
          return;
        }

        // 身份证反面信息 - 直接使用接口返回的IdCardExpiryDate字段
        const idCardExpiryDate = (data as any).IdCardExpiryDate;
        if (idCardExpiryDate) {
          try {
            // 处理接口返回的IdCardExpiryDate字段
            let parsedDate: Date | null = null;
            const expiryDateStr = idCardExpiryDate.toString().trim();

            // 情况1: 直接是完整的日期时间格式 yyyy/MM/dd HH:mm:ss
            if (
              /^\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}$/.test(expiryDateStr)
            ) {
              parsedDate = new Date(expiryDateStr);
            }
            // 情况2: 只有日期部分 yyyy/MM/dd
            else if (/^\d{4}\/\d{2}\/\d{2}$/.test(expiryDateStr)) {
              parsedDate = new Date(expiryDateStr + " 00:00:00");
            }
            // 情况3: yyyy-MM-dd 格式
            else if (/^\d{4}-\d{2}-\d{2}$/.test(expiryDateStr)) {
              parsedDate = new Date(expiryDateStr + "T00:00:00");
            }
            // 情况4: yyyy.MM.dd 格式
            else if (/^\d{4}\.\d{2}\.\d{2}$/.test(expiryDateStr)) {
              const normalizedDate = expiryDateStr.replace(/\./g, "/");
              parsedDate = new Date(normalizedDate + " 00:00:00");
            }
            // 情况5: yyyyMMdd 格式
            else if (/^\d{8}$/.test(expiryDateStr)) {
              const year = expiryDateStr.substring(0, 4);
              const month = expiryDateStr.substring(4, 6);
              const day = expiryDateStr.substring(6, 8);
              parsedDate = new Date(`${year}/${month}/${day} 00:00:00`);
            }
            // 情况6: 其他格式，尝试直接解析
            else {
              parsedDate = new Date(expiryDateStr);
            }

            // 验证日期是否有效并设置
            if (parsedDate && !isNaN(parsedDate.getTime())) {
              // 检查日期是否超过50年（约18250天）
              const currentDate = new Date();
              const daysDifference = Math.abs(
                (parsedDate.getTime() - currentDate.getTime()) /
                  (1000 * 60 * 60 * 24),
              );

              if (daysDifference > 18250) {
                // 如果超过50年，保存原始日期但设置显示状态为"长期有效"
                formData.value.IdCardExpiryDate = parsedDate; // 保存原始日期用于数据提交
                idCardExpiryDisplayState.value = "long-term"; // 设置显示状态
                // 不调用 handleFieldChange，避免触发不必要的UI更新
              } else {
                // 正常日期，使用识别到的日期
                formData.value.IdCardExpiryDate = parsedDate;
                idCardExpiryDisplayState.value = "normal"; // 重置显示状态为正常

                // 触发字段变化事件，确保UI更新
                const year = parsedDate.getFullYear();
                const month = String(parsedDate.getMonth() + 1).padStart(
                  2,
                  "0",
                );
                const day = String(parsedDate.getDate()).padStart(2, "0");
                const dateString = `${year}-${month}-${day}`;
                handleFieldChange("IdCardExpiryDate", dateString);
              }
            }
          } catch (error) {
            // 解析身份证有效期出错
          }
        }

        // 兼容处理：如果IdCardExpiryDate字段不存在，尝试从ValidPeriod解析
        else if (data.ValidPeriod) {
          try {
            const validPeriod = data.ValidPeriod;
            if (validPeriod.includes("-") && !validPeriod.includes("长期")) {
              const endDate = validPeriod.split("-")[1];
              if (endDate) {
                const endDateStr = endDate.trim();
                let parsedDate: Date | null = null;

                if (/^\d{4}\.\d{2}\.\d{2}$/.test(endDateStr)) {
                  const normalizedDate = endDateStr.replace(/\./g, "/");
                  parsedDate = new Date(normalizedDate + " 00:00:00");
                } else if (/^\d{4}\/\d{2}\/\d{2}$/.test(endDateStr)) {
                  parsedDate = new Date(endDateStr + " 00:00:00");
                }

                if (parsedDate && !isNaN(parsedDate.getTime())) {
                  // 检查日期是否超过50年（约18250天）
                  const currentDate = new Date();
                  const daysDifference = Math.abs(
                    (parsedDate.getTime() - currentDate.getTime()) /
                      (1000 * 60 * 60 * 24),
                  );

                  if (daysDifference > 18250) {
                    // 如果超过50年，保存原始日期但设置显示状态为"长期有效"
                    formData.value.IdCardExpiryDate = parsedDate; // 保存原始日期用于数据提交
                    idCardExpiryDisplayState.value = "long-term"; // 设置显示状态
                    // 不调用 handleFieldChange，避免触发不必要的UI更新
                  } else {
                    // 正常日期，使用识别到的日期
                    formData.value.IdCardExpiryDate = parsedDate;
                    idCardExpiryDisplayState.value = "normal"; // 重置显示状态为正常
                    const year = parsedDate.getFullYear();
                    const month = String(parsedDate.getMonth() + 1).padStart(
                      2,
                      "0",
                    );
                    const day = String(parsedDate.getDate()).padStart(2, "0");
                    const dateString = `${year}-${month}-${day}`;
                    handleFieldChange("IdCardExpiryDate", dateString);
                  }
                }
              }
            }
          } catch (error) {
            // 从ValidPeriod解析有效期出错
          }
        }

        uni.showToast({
          title: "身份证反面信息识别成功",
          icon: "success",
        });
      }
    } else {
      // 身份证识别失败时的详细提示
      let failureMessage = "身份证识别失败";
      if (response.Message) {
        failureMessage = response.Message;
      } else if (response.Code !== 200) {
        failureMessage = `识别服务异常(错误码:${response.Code})`;
      }

      // 清除失败的图片数据
      if (cardType === "front") {
        formData.value.IdCardFrontPhotoId = null;
        fileValues.value["IdCardFrontPhotoId"] = [];
      } else if (cardType === "back") {
        formData.value.IdCardBackPhotoId = null;
        fileValues.value["IdCardBackPhotoId"] = [];
      }

      // 强制刷新UI组件和触发验证更新
      nextTick(() => {
        // 已清除身份证识别失败图片
        if (formRef.value) {
          const fieldKey =
            cardType === "front" ? "IdCardFrontPhotoId" : "IdCardBackPhotoId";
          formRef.value.validateField(fieldKey);
        }
      });

      uni.showModal({
        title: "身份证识别失败",
        content: `${failureMessage}\n图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证${
          cardType === "front" ? "正面" : "反面"
        }\n2. 身份证照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示\n\n您可以重新拍摄上传，或手动填写相关信息`,
        confirmText: "我知道了",
        showCancel: false,
      });
    }
  } catch (error) {
    uni.hideLoading();

    // 清除异常时的图片数据
    if (cardType === "front") {
      formData.value.IdCardFrontPhotoId = null;
      fileValues.value["IdCardFrontPhotoId"] = [];
    } else if (cardType === "back") {
      formData.value.IdCardBackPhotoId = null;
      fileValues.value["IdCardBackPhotoId"] = [];
    }

    // 强制刷新UI组件和触发验证更新
    nextTick(() => {
      // 已清除身份证异常图片
      if (formRef.value) {
        const fieldKey =
          cardType === "front" ? "IdCardFrontPhotoId" : "IdCardBackPhotoId";
        formRef.value.validateField(fieldKey);
      }
    });

    // 网络或系统错误时的详细提示
    uni.showModal({
      title: "身份证识别失败",
      content: `识别服务暂时不可用，可能是网络连接问题。图片已清除，请重新上传。\n\n建议操作：\n1. 确认上传的是身份证${
        cardType === "front" ? "正面" : "反面"
      }\n2. 检查网络连接\n3. 稍后重新尝试\n4. 或手动填写身份证信息`,
      confirmText: "我知道了",
      showCancel: false,
    });
  }
};

// 图片样式配置现在在配置文件中定义

// 获取图片URL - 参考员工档案的实现
const getImageUrl = (fileId: string | null) => {
  if (!fileId) return "";
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 这些函数已经被统一的 deleteFile 和 deleteIdCardFile 函数替代

// 简历文件相关函数已经被统一的文件处理函数替代

// 转换部门树数据为uni-data-picker格式
const convertToTreeData = (treeData: any[]): any[] => {
  return treeData.map((item) => {
    const hasChildren =
      item.Children && Array.isArray(item.Children) && item.Children.length > 0;
    const result = {
      value: item.Value || item.Id,
      text: item.Text || item.Tag,
      children: hasChildren ? convertToTreeData(item.Children) : [],
    };

    return result;
  });
};

// 统一的部门选择处理函数
const selectDepartment = async (
  departmentId: string,
  departmentName: string,
) => {
  // 如果正在确认中或数据加载中，直接返回
  if (isConfirming.value || isDataLoading.value) {
    return;
  }

  // 查找完整的部门信息
  const department = findDepartmentById(departmentTreeData.value, departmentId);
  if (!department) {
    uni.showToast({
      title: "部门信息不存在",
      icon: "none",
    });
    return;
  }

  // 检查是否有子部门
  const hasChildren =
    Array.isArray(department.children) && department.children.length > 0;

  if (hasChildren) {
    // 有子部门，显示确认对话框
    isConfirming.value = true;

    uni.showModal({
      title: "确认选择",
      content: `确定选择父级部门"${departmentName}"吗？\n（该部门下还有${department.children.length}个子部门）`,
      confirmText: "确定选择",
      cancelText: "继续选择",
      success: (res) => {
        if (res.confirm) {
          // 用户确认选择父级部门
          confirmDepartmentSelection(departmentId, departmentName);
        }
        isConfirming.value = false;
      },
      fail: () => {
        isConfirming.value = false;
      },
    });
  } else {
    // 叶子部门，直接选择
    confirmDepartmentSelection(departmentId, departmentName);
  }
};

// 确认部门选择
const confirmDepartmentSelection = async (
  departmentId: string,
  departmentName: string,
) => {
  // 设置部门ID
  formData.value.GroupId = departmentId;

  // 清空当前已选择的工作岗位，避免数据不一致
  formData.value.JobPositionId = null;

  // 触发字段变化事件
  handleFieldChange("GroupId", departmentId);

  // 加载该部门下的岗位列表
  await loadJobPositionsByDepartment(departmentId);

  // 显示成功提示
  uni.showToast({
    title: `已选择部门：${departmentName}`,
    icon: "none",
    duration: 2000,
  });

  // 关闭选择器弹窗
  if (
    departmentPicker.value &&
    typeof departmentPicker.value.hide === "function"
  ) {
    departmentPicker.value.hide();
  }
};

// 处理部门选择变化
const handleDepartmentChange = (e: any) => {
  // 直接从事件中获取选择的部门信息
  const selectedDepartment = e.detail.value;

  if (selectedDepartment && selectedDepartment.value) {
    const departmentId = selectedDepartment.value;
    const departmentName = selectedDepartment.text;

    // 调用统一的部门选择处理函数
    selectDepartment(departmentId, departmentName);
  }
};

// 处理自定义部门选择器变化
const handleCustomDepartmentChange = async (
  departmentId: string,
  item: any,
) => {
  // 设置部门ID
  formData.value.GroupId = departmentId;

  // 清空当前已选择的工作岗位，避免数据不一致
  formData.value.JobPositionId = null;

  // 触发字段变化事件
  handleFieldChange("GroupId", departmentId);

  // 加载该部门下的岗位列表
  await loadJobPositionsByDepartment(departmentId);

  // 显示成功提示
  uni.showToast({
    title: `已选择部门：${item.text}`,
    icon: "none",
    duration: 2000,
  });
};

// 根据ID查找部门信息的辅助函数
const findDepartmentById = (treeData: any[], targetId: string): any => {
  for (const item of treeData) {
    if (item.value === targetId) {
      return item;
    }
    if (Array.isArray(item.children) && item.children.length > 0) {
      const found = findDepartmentById(item.children, targetId);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 处理部门节点点击
const handleDepartmentNodeClick = (node: any) => {
  // 检查节点是否有必要的信息
  if (node && (node.value || node.id)) {
    const departmentId = node.value || node.id;
    const departmentName = node.text || node.label || node.name;

    // 调用统一的部门选择处理函数
    selectDepartment(departmentId, departmentName);

    // 对于有子部门的节点，阻止默认的选择行为，让用户通过确认框来选择
    const department = findDepartmentById(
      departmentTreeData.value,
      departmentId,
    );
    if (
      department &&
      Array.isArray(department.children) &&
      department.children.length > 0
    ) {
      return false; // 阻止默认选择行为
    }

    return true; // 允许默认选择行为
  }
};

// 根据部门ID加载岗位选项
const loadJobPositionsByDepartment = async (
  departmentId: string,
  showLoading: boolean = true,
) => {
  try {
    if (!departmentId) {
      // 如果没有部门ID，清空岗位选项
      jobPositionOptions.value = [];
      return;
    }

    // 只有在非数据加载状态时才显示loading
    if (showLoading && !isDataLoading.value) {
      uni.showLoading({
        title: "加载岗位列表...",
        mask: true,
      });
    }

    const jobRes = await api.GetSysJobPositions(departmentId);
    if (jobRes && Array.isArray(jobRes)) {
      jobPositionOptions.value = jobRes.map((item: any) => ({
        value: item.Value || item.Id,
        text: item.Text || item.Name,
      }));
    } else {
      jobPositionOptions.value = [];
    }

    if (showLoading && !isDataLoading.value) {
      uni.hideLoading();
    }
  } catch (error) {
    if (showLoading && !isDataLoading.value) {
      uni.hideLoading();
    }

    // 加载失败时清空岗位选项
    jobPositionOptions.value = [];

    // 只有在用户操作时才显示错误提示
    if (!isDataLoading.value) {
      uni.showToast({
        title: "加载岗位列表失败",
        icon: "none",
        duration: 2000,
      });
    }
  }
};

// 加载工作信息选项数据
const loadWorkOptions = async () => {
  try {
    // 设置数据加载标志位，避免在初始化时触发确认弹框
    isDataLoading.value = true;

    // 加载公司列表
    const orgRes = await api.getOrgList();
    if (orgRes && Array.isArray(orgRes)) {
      orgOptions.value = orgRes.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    // 加载部门列表
    const groupRes = await api.getGroupList();
    if (groupRes && Array.isArray(groupRes)) {
      groupOptions.value = groupRes.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    // 注意：不再在这里加载岗位列表，改为根据部门动态加载
    // 初始化时岗位选项为空，等待用户选择部门后再加载
    jobPositionOptions.value = [];

    // 加载部门树数据
    const treeRes = await api.GetParentsTree();
    if (treeRes && Array.isArray(treeRes)) {
      // 保存原始数据用于自定义部门选择器
      rawDepartmentData.value = treeRes;
      // 转换数据用于uni-data-picker
      departmentTreeData.value = convertToTreeData(treeRes);
    }

    // 如果初始化时已有部门ID，则加载对应的岗位列表（初始化时不显示loading）
    if (formData.value.GroupId) {
      await loadJobPositionsByDepartment(formData.value.GroupId, false);
    }

    // 使用setTimeout确保标志位在所有异步操作完成后重置
    setTimeout(() => {
      isDataLoading.value = false;
    }, 100); // 给一个小的延迟确保所有操作完成
  } catch (error) {
    // 加载工作信息选项失败，也要重置标志位
    setTimeout(() => {
      isDataLoading.value = false;
    }, 100);
  }
};

// 公司变化现在通过统一的 handleFieldChange 处理

// 处理退伍军人选择变化（现在通过统一的 handleFieldChange 处理）
// 所有选项数据现在都在配置文件 basicInfoFormConfig.ts 中定义

// 在组件挂载时监听事件，卸载时清理
onMounted(() => {
  uni.$on("portrait-camera-result", handlePortraitCameraResult);
});

onUnmounted(() => {
  uni.$off("portrait-camera-result", handlePortraitCameraResult);
});

const handlePortraitCameraResult = async (data: {
  success: boolean;
  fieldKey: string;
  fieldLabel: string;
  fileId?: string;
  path?: string;
  size?: number;
  error?: string;
}) => {
  if (data.success && data.fileId && data.fieldKey) {
    try {
      // 显示AI处理loading
      uni.showLoading({
        title: "正在生成证件照...",
        mask: true,
      });

      console.log("开始人像验证，图片ID:", data.fileId);
      const validateResult = await api.validatePortrait({
        ImageId: data.fileId,
      });
      console.log("人像验证结果:", validateResult);

      // 隐藏loading
      uni.hideLoading();

      if (validateResult.Code !== 200) {
        // 验证失败，显示错误信息
        uni.showToast({
          title: validateResult.Message,
          icon: "none",
          duration: 3000,
        });
        return;
      } else {
        // 验证通过，显示成功提示
        uni.showToast({
          title: validateResult.Message || "证件照生成成功",
          icon: "success",
          duration: 1500,
        });

        // 使用处理后的图片ID
        if (validateResult.Data) {
          const processedImageId = validateResult.Data;
          console.log("使用处理后的图片ID:", processedImageId);
          (formData.value as any)[data.fieldKey] = processedImageId;
        } else {
          // 如果没有返回处理后的图片，使用原图片
          (formData.value as any)[data.fieldKey] = data.fileId;
        }

        // 触发表单验证更新
        nextTick(() => {
          if (formRef.value) {
            formRef.value.clearValidate(data.fieldKey);
          }
        });
      }
    } catch (error) {
      // 隐藏loading
      uni.hideLoading();

      console.error("人像验证失败:", error);
      uni.showToast({
        title: "照片处理失败，请重试",
        icon: "none",
        duration: 3000,
      });
    }
  } else if (data.error) {
    uni.showToast({
      title: data.error,
      icon: "none",
    });
  }
};

// 初始化图片回显数据
const initImageDisplay = () => {
  // 个人照片回显（portrait-camera类型字段无需在fileValues中处理，直接在模板中显示）
  // PhotoId字段现在使用portrait-camera类型，不需要在fileValues中处理

  // 身份证正面回显
  if (
    formData.value.IdCardFrontPhotoId &&
    !fileValues.value["IdCardFrontPhotoId"]?.length
  ) {
    fileValues.value["IdCardFrontPhotoId"] = [
      {
        name: "身份证正面",
        url: getImageUrl(formData.value.IdCardFrontPhotoId),
        extname: "jpg",
        size: 0,
        fileID: formData.value.IdCardFrontPhotoId,
      },
    ];
  }

  // 身份证反面回显
  if (
    formData.value.IdCardBackPhotoId &&
    !fileValues.value["IdCardBackPhotoId"]?.length
  ) {
    fileValues.value["IdCardBackPhotoId"] = [
      {
        name: "身份证反面",
        url: getImageUrl(formData.value.IdCardBackPhotoId),
        extname: "jpg",
        size: 0,
        fileID: formData.value.IdCardBackPhotoId,
      },
    ];
  }

  // 退伍证图片回显
  if (
    formData.value.VeteranCertificateId &&
    !fileValues.value["VeteranCertificateId"]?.length
  ) {
    fileValues.value["VeteranCertificateId"] = [
      {
        name: "退伍证图片",
        url: getImageUrl(formData.value.VeteranCertificateId),
        extname: "jpg",
        size: 0,
        fileID: formData.value.VeteranCertificateId,
      },
    ];
  }
};

// 监听props变化 - 实现数据回显
watch(
  () => props.modelValue,
  async (newVal, oldVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 检查是否是真正的数据变化（比如从后端加载的新数据）
      // 而不是用户输入导致的循环更新
      const isRealDataChange =
        !oldVal ||
        Object.keys(newVal).some((key) => {
          // 检查关键字段是否有实质性变化
          if (["ID", "BillCode", "Name", "StaffNo", "IdCardNo"].includes(key)) {
            return (newVal as any)[key] !== (oldVal as any)[key];
          }
          return false;
        });

      if (!isRealDataChange) {
        // 如果不是真正的数据变化，直接返回，避免循环
        return;
      }

      // 设置数据加载标志位，防止触发部门确认弹框
      isDataLoading.value = true;

      // 合并新数据到表单
      formData.value = { ...formData.value, ...newVal };

      // 如果员工工号为空且有用户信息，自动填充
      if (!formData.value.StaffNo && userInfo.value?.ITCode) {
        formData.value.StaffNo = userInfo.value.ITCode;
      }

      // 处理退伍军人字段的数据类型转换
      if (
        formData.value.IsVeteran !== null &&
        formData.value.IsVeteran !== undefined
      ) {
        // 确保退伍军人字段是字符串类型，与选项配置保持一致
        if (typeof formData.value.IsVeteran === "boolean") {
          (formData.value as any).IsVeteran = formData.value.IsVeteran
            ? "true"
            : "false";
        } else if (
          formData.value.IsVeteran !== "true" &&
          formData.value.IsVeteran !== "false"
        ) {
          // 如果是其他值，转换为字符串
          (formData.value as any).IsVeteran = formData.value.IsVeteran
            ? "true"
            : "false";
        }
      }

      // 计算工龄（如果有参加工作时间）
      if (formData.value.JoinWorkDate) {
        const joinWorkDate = new Date(formData.value.JoinWorkDate);
        const today = new Date();
        const years = today.getFullYear() - joinWorkDate.getFullYear();
        const monthDiff = today.getMonth() - joinWorkDate.getMonth();

        if (
          monthDiff < 0 ||
          (monthDiff === 0 && today.getDate() < joinWorkDate.getDate())
        ) {
          formData.value.WorkYears = Math.max(0, years - 1);
        } else {
          formData.value.WorkYears = Math.max(0, years);
        }
      } else {
        formData.value.WorkYears = 0;
      }

      // 计算司龄（如果有入职日期）
      if (formData.value.HireDate) {
        const hireDate = new Date(formData.value.HireDate);
        const today = new Date();
        const years = today.getFullYear() - hireDate.getFullYear();
        const monthDiff = today.getMonth() - hireDate.getMonth();

        if (
          monthDiff < 0 ||
          (monthDiff === 0 && today.getDate() < hireDate.getDate())
        ) {
          formData.value.CompanyYears = Math.max(0, years - 1);
        } else {
          formData.value.CompanyYears = Math.max(0, years);
        }
      } else {
        formData.value.CompanyYears = 0;
      }

      // 初始化图片回显
      initImageDisplay();

      // 确保在所有操作完成后重置标志位
      nextTick(() => {
        isDataLoading.value = false;
      });
    }
  },
  { deep: true, immediate: true },
);

// 监听formData变化，同步到父组件 - 添加标志位检查
watch(
  formData,
  (newVal) => {
    // 只有非数据加载时才emit
    if (!isDataLoading.value) {
      emits("update:modelValue", newVal);
    }
  },
  { deep: true },
);

// 监听出生日期变化，自动计算年龄
watch(
  () => formData.value.BirthDate,
  (newDate) => {
    if (newDate) {
      const birthDate = new Date(newDate);
      const today = new Date();
      const age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < birthDate.getDate())
      ) {
        formData.value.Age = age - 1;
      } else {
        formData.value.Age = age;
      }
    } else {
      formData.value.Age = null;
    }
  },
);

// 监听参加工作时间变化，自动计算工龄
watch(
  () => formData.value.JoinWorkDate,
  (newDate) => {
    if (newDate) {
      const joinWorkDate = new Date(newDate);
      const today = new Date();
      const years = today.getFullYear() - joinWorkDate.getFullYear();
      const monthDiff = today.getMonth() - joinWorkDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < joinWorkDate.getDate())
      ) {
        formData.value.WorkYears = years - 1;
      } else {
        formData.value.WorkYears = years;
      }

      // 确保工龄不为负数
      if (formData.value.WorkYears < 0) {
        formData.value.WorkYears = 0;
      }
    } else {
      formData.value.WorkYears = 0;
    }
  },
);

// 监听入职日期变化，自动计算司龄
watch(
  () => formData.value.HireDate,
  (newDate) => {
    if (newDate) {
      const hireDate = new Date(newDate);
      const today = new Date();
      const years = today.getFullYear() - hireDate.getFullYear();
      const monthDiff = today.getMonth() - hireDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < hireDate.getDate())
      ) {
        formData.value.CompanyYears = years - 1;
      } else {
        formData.value.CompanyYears = years;
      }

      // 确保司龄不为负数
      if (formData.value.CompanyYears < 0) {
        formData.value.CompanyYears = 0;
      }
    } else {
      formData.value.CompanyYears = 0;
    }
  },
);

// 获取用户信息并自动填充员工工号
const loadUserInfo = () => {
  const cachedUserInfo = uni.getStorageSync("userInfo");
  if (cachedUserInfo) {
    userInfo.value = cachedUserInfo;

    // 自动填充员工工号为用户的ITCode
    if (cachedUserInfo.ITCode && !formData.value.StaffNo) {
      formData.value.StaffNo = cachedUserInfo.ITCode;
    }
  }
};

// 组件挂载时加载工作信息选项数据和用户信息
onMounted(() => {
  loadWorkOptions();
  loadUserInfo();
});

// 字段变化处理
const handleFieldChange = (field: string, value: any) => {
  // 如果是事件对象，提取实际的值
  let actualValue = value;
  if (value && typeof value === "object" && value.detail !== undefined) {
    // uni-easyinput blur事件的值在 value.detail.value 中
    actualValue = value.detail.value;
  } else if (value && typeof value === "object" && value.target !== undefined) {
    // 标准DOM事件的值在 value.target.value 中
    actualValue = value.target.value;
  }

  // 直接更新formData中对应的字段
  (formData.value as any)[field] = actualValue;

  // 特殊处理退伍军人字段
  if (field === "IsVeteran") {
    // 直接使用字符串值，与选项配置保持一致
    (formData.value as any)[field] = actualValue;

    // 如果选择否，清空退伍证图片
    if (actualValue === "false" || !actualValue) {
      formData.value.VeteranCertificateId = null;
      fileValues.value["VeteranCertificateId"] = [];
    }
  }

  // 触发数据更新
  emits("update:modelValue", formData.value);
};

// 人像相机相关方法 - 跳转到独立页面
const handlePortraitCapture = (field: FieldConfig) => {
  // 检查相机权限
  uni.authorize({
    scope: "scope.camera",
    success: () => {
      // 显示相机界面
      showPortraitCamera(field);
    },
    fail: () => {
      uni.showModal({
        title: "需要相机权限",
        content: "请在设置中开启相机权限以使用拍照功能",
        confirmText: "去设置",
        success: (res) => {
          if (res.confirm) {
            uni.openSetting();
          }
        },
      });
    },
  });
};

const showPortraitCamera = (field: FieldConfig) => {
  // 导航到相机页面，由于相机组件需要全屏显示
  uni.navigateTo({
    url: `/pages/portrait-camera/index?fieldKey=${
      field.key
    }&fieldLabel=${encodeURIComponent(field.label)}&maxSize=${
      field.fileConfig?.maxSize || 5
    }&quality=${field.fileConfig?.quality || 0.8}`,
  });
};

const handlePortraitPreview = (field: FieldConfig) => {
  // 预览图片
  if ((formData.value as any)[field.key]) {
    uni.previewImage({
      urls: [getImageUrl((formData.value as any)[field.key])],
    });
  }
};

const deletePortraitPhoto = (field: FieldConfig) => {
  (formData.value as any)[field.key] = null;

  // 触发表单验证更新
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField(field.key);
    }
  });
};

// 这些旧的图片上传函数已经被统一的文件处理函数替代

// 旧的校验函数已被 uni-forms 的校验系统替代

// 保存处理 - 简化逻辑，让父组件统一处理验证和错误
const handleSave = async () => {
  // 直接触发保存事件，让父组件处理验证和保存逻辑
  emits("save", formData.value);
};

// 暴露方法供父组件调用
defineExpose({
  validate: async (): Promise<boolean> => {
    try {
      await formRef.value.validate();
      return true;
    } catch (error) {
      // 抛出错误让父组件统一处理
      throw error;
    }
  },
  reset: () => {
    // 重置表单
    Object.keys(formData.value).forEach((key) => {
      if (key === "BillStatus" || key === "WorkflowStatus") {
        (formData.value as any)[key] = 1;
      } else if (key === "Age") {
        (formData.value as any)[key] = null;
      } else if (typeof (formData.value as any)[key] === "string") {
        (formData.value as any)[key] = "";
      } else {
        (formData.value as any)[key] = null;
      }
    });

    // 清空文件上传
    fileValues.value = {};

    // 重置身份证有效期显示状态
    idCardExpiryDisplayState.value = "normal";

    // 重置表单校验状态
    formRef.value?.clearValidate();
  },
  // 新增方法：加载数据
  loadData: async (data: Partial<ISysPersonRepairBill>) => {
    // 设置数据加载标志位，防止触发部门确认弹框
    isDataLoading.value = true;

    formData.value = { ...formData.value, ...data };

    // 如果员工工号为空且有用户信息，自动填充
    if (!formData.value.StaffNo && userInfo.value?.ITCode) {
      formData.value.StaffNo = userInfo.value.ITCode;
    }

    // 处理退伍军人字段的数据类型转换
    if (
      formData.value.IsVeteran !== null &&
      formData.value.IsVeteran !== undefined
    ) {
      // 确保退伍军人字段是字符串类型，与选项配置保持一致
      if (typeof formData.value.IsVeteran === "boolean") {
        (formData.value as any).IsVeteran = formData.value.IsVeteran
          ? "true"
          : "false";
      } else if (
        formData.value.IsVeteran !== "true" &&
        formData.value.IsVeteran !== "false"
      ) {
        // 如果是其他值，转换为字符串
        (formData.value as any).IsVeteran = formData.value.IsVeteran
          ? "true"
          : "false";
      }
    }

    // 计算工龄（如果有参加工作时间）
    if (formData.value.JoinWorkDate) {
      const joinWorkDate = new Date(formData.value.JoinWorkDate);
      const today = new Date();
      const years = today.getFullYear() - joinWorkDate.getFullYear();
      const monthDiff = today.getMonth() - joinWorkDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < joinWorkDate.getDate())
      ) {
        formData.value.WorkYears = Math.max(0, years - 1);
      } else {
        formData.value.WorkYears = Math.max(0, years);
      }
    } else {
      formData.value.WorkYears = 0;
    }

    // 计算司龄（如果有入职日期）
    if (formData.value.HireDate) {
      const hireDate = new Date(formData.value.HireDate);
      const today = new Date();
      const years = today.getFullYear() - hireDate.getFullYear();
      const monthDiff = today.getMonth() - hireDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < hireDate.getDate())
      ) {
        formData.value.CompanyYears = Math.max(0, years - 1);
      } else {
        formData.value.CompanyYears = Math.max(0, years);
      }
    } else {
      formData.value.CompanyYears = 0;
    }

    // 如果有部门ID，加载对应的岗位列表（数据回显时不显示loading）
    if (formData.value.GroupId) {
      await loadJobPositionsByDepartment(formData.value.GroupId, false);
    }

    // 初始化图片回显
    nextTick(() => {
      initImageDisplay();
      // 确保在所有操作完成后重置标志位
      isDataLoading.value = false;
    });
  },
});
</script>

<style lang="scss" scoped>
.basic-info-form {
  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .section-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #374151;
      }
    }
  }

  .info-module {
    background: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .module-header {
      background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%);
      padding: 24rpx;
      display: flex;
      align-items: center;
      gap: 16rpx;

      .module-icon {
        width: 48rpx;
        height: 48rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
      }

      .module-title {
        flex: 1;

        .title {
          display: block;
          font-size: 32rpx;
          font-weight: bold;
          color: #ffffff;
          line-height: 1.2;
        }

        .subtitle {
          display: block;
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.8);
          margin-top: 4rpx;
          line-height: 1.2;
        }
      }
    }

    .module-content {
      padding: 32rpx;
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(1, 1fr);

    @media (min-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (min-width: 1024px) {
      grid-template-columns: repeat(3, 1fr);
    }

    .form-item {
      &.full-width {
        grid-column: 1 / -1;
      }

      .form-label {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        color: #374151;
        margin-bottom: 12rpx;

        .required {
          color: #ef4444;
        }
      }
    }
  }

  .portrait-camera-container {
    margin-top: 16rpx;

    .portrait-preview-area {
      display: flex;
      flex-direction: column;
      align-items: start;

      .portrait-preview {
        position: relative;
        display: inline-block;

        .portrait-image {
          width: 320rpx;
          height: 400rpx;
          border-radius: 16rpx;
          border: 2rpx solid #e5e7eb;
          display: block;
          object-fit: cover;
        }

        .delete-icon-button {
          position: absolute;
          top: -8rpx;
          right: -8rpx;
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.9);
          border: 2rpx solid #e5e7eb;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          &:active {
            background: rgba(255, 255, 255, 0.8);
          }
        }
      }

      .portrait-capture {
        .capture-trigger {
          width: 320rpx;
          height: 400rpx;
          border: 4rpx dashed #d1d5db;
          border-radius: 16rpx;
          background: #f9fafb;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 16rpx;
          cursor: pointer;

          &:active {
            background: #f3f4f6;
            border-color: #9ca3af;
          }

          .capture-text {
            font-size: 28rpx;
            color: #6b7280;
            text-align: center;
            padding: 0 16rpx;
          }
        }
      }
    }
  }

  .photo-upload-container,
  .id-card-upload-container,
  .file-upload-container {
    margin-top: 16rpx;

    .id-card-item {
      margin-bottom: 24rpx;

      .id-card-label {
        display: block;
        font-size: 26rpx;
        color: #374151;
        margin-bottom: 12rpx;
        font-weight: 500;
      }
    }

    .resume-preview-btn {
      margin-top: 16rpx;
      padding: 16rpx 24rpx;
      background: #f0f9ff;
      border: 2rpx solid #e0f2fe;
      border-radius: 12rpx;
      cursor: pointer;
      transition: all 0.3s ease;

      &:active {
        background: #e0f2fe;
        transform: scale(0.98);
      }

      .preview-content {
        display: flex;
        align-items: center;
        justify-content: center;

        .preview-text {
          font-size: 28rpx;
          color: #374151;
          font-weight: 500;
        }
      }
    }

    .upload-tips {
      margin-top: 12rpx;
      padding: 12rpx 16rpx;
      background: #f8fafc;
      border-radius: 8rpx;
      border-left: 4rpx solid #7c3aed;

      text {
        font-size: 22rpx;
        color: #6b7280;
        display: block;
        line-height: 1.5;
      }
    }
  }

  .section-actions {
    margin-top: 48rpx;
    display: flex;
    justify-content: center;
    padding: 24rpx 0;
    border-top: 2rpx solid #e5e7eb;

    .custom-button {
      min-width: 300rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 16rpx 32rpx;
      border-radius: 12rpx;
      border: none;
      font-size: 28rpx;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;

      &.primary-button {
        background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%);
        color: #ffffff;
        box-shadow: 0 8rpx 20rpx rgba(124, 58, 237, 0.3);

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 12rpx rgba(124, 58, 237, 0.4);
        }
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none !important;
      }
    }
  }
}

// 组件库样式覆盖
:deep(.uni-easyinput__placeholder-class) {
  color: #9ca3af !important;
}

// 修复移动端placeholder居中问题
:deep(.uni-easyinput__content-input) {
  display: flex !important;
  align-items: center !important;
  line-height: normal !important;

  &::placeholder {
    line-height: normal !important;
    display: flex !important;
    align-items: center !important;
  }
}

:deep(.uni-datetime-picker--x) {
  width: 100%;
}

:deep(.uni-data-select) {
  width: 100%;
}

:deep(.uni-tag--primary) {
  background: #3b82f6 !important;
}

:deep(.uni-easyinput) {
  border-radius: 12rpx !important;
}

:deep(.uni-data-select__input-box) {
  border-radius: 12rpx !important;
}

/* 人像相机样式 */
.portrait-camera-container {
  .portrait-preview {
    text-align: center;

    .portrait-image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 16rpx;
      border: 2rpx solid #e5e7eb;
      margin-bottom: 24rpx;
    }

    .portrait-actions {
      display: flex;
      gap: 16rpx;
      justify-content: center;

      .portrait-action-btn {
        padding: 16rpx 24rpx;
        border-radius: 12rpx;
        border: none;
        font-size: 24rpx;
        cursor: pointer;

        &.retake-btn {
          background: #7c3aed;
          color: #ffffff;

          &:active {
            background: #6d28d9;
          }
        }

        &.delete-btn {
          background: #ef4444;
          color: #ffffff;

          &:active {
            background: #dc2626;
          }
        }

        &::after {
          border: none;
        }
      }
    }
  }

  .portrait-capture-area {
    text-align: center;

    .capture-placeholder {
      padding: 60rpx 40rpx;
      border: 2rpx dashed #d1d5db;
      border-radius: 16rpx;
      margin-bottom: 24rpx;
      background: #f9fafb;

      .capture-text {
        display: block;
        margin-top: 16rpx;
        font-size: 28rpx;
        color: #6b7280;
      }
    }

    .capture-button {
      background: #7c3aed;
      color: #ffffff;
      border: none;
      border-radius: 12rpx;
      padding: 20rpx 40rpx;
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin: 0 auto;
      cursor: pointer;

      &:active {
        background: #6d28d9;
        transform: scale(0.98);
      }

      &::after {
        border: none;
      }

      .capture-btn-text {
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }
}

/* 表单提示样式 */
.form-tips {
  margin-top: 8rpx;
  padding: 8rpx 12rpx;
  background-color: #f8f9ff;
  border-radius: 8rpx;
  border-left: 3rpx solid #7c3aed;
}

.form-tips text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
}
</style>
